package com.ruoyi.web.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.web.domain.DebtsSectionAttachment;
import com.ruoyi.web.domain.dto.DebtsSectionDto;
import com.ruoyi.web.domain.export.DebtsSectionExport;
import com.ruoyi.web.domain.vo.DebtsSectionVo;
import com.ruoyi.web.handler.HeaderStyleHandler;
import com.ruoyi.web.service.DebtsSectionAttachmentService;
import com.ruoyi.web.service.DebtsSectionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "清欠专区控制层")
@RestController
@RequestMapping("/debts-section")
public class DebtsSectionController extends BaseController {

    @Autowired
    private DebtsSectionService debtsSectionService;

    @Autowired
    private DebtsSectionAttachmentService debtsSectionAttachmentService;

    @ApiOperation("清欠表单提交")
    @PostMapping
    public AjaxResult addDebts(@RequestBody DebtsSectionDto dto){
        debtsSectionService.addDebts(dto);
        return AjaxResult.success();
    }

    @ApiOperation("查询清欠数据列表")
    @GetMapping("/list")
    public TableDataInfo getList(DebtsSectionDto dto){
        startPage();
        List<DebtsSectionVo> list = debtsSectionService.getList(dto);
        return getDataTable(list);
    }

    @ApiOperation("查询清欠数据详情")
    @GetMapping("/{baseId}")
    public AjaxResult getDetails(@PathVariable("baseId") Long baseId){
        return AjaxResult.success(debtsSectionService.getDetails(baseId));
    }

    @ApiOperation("指派清欠数据")
    @PutMapping("/dispatch")
    public AjaxResult dispatchDebts(@RequestBody DebtsSectionDto dto){
        debtsSectionService.dispatchDebts(dto);
        return AjaxResult.success();
    }

    @ApiOperation("处理清欠数据")
    @PutMapping("/deal")
    public AjaxResult dealDebts(@RequestBody DebtsSectionDto dto){
        debtsSectionService.dealDebts(dto);
        return AjaxResult.success();
    }

    @ApiOperation("删除清欠")
    @DeleteMapping("/{baseId}")
    public AjaxResult deleteById(@PathVariable("baseId") String baseId){
        debtsSectionAttachmentService.remove(new LambdaQueryWrapper<DebtsSectionAttachment>().eq(DebtsSectionAttachment::getDebtsId, baseId));
        debtsSectionService.removeById(baseId);
        return AjaxResult.success();
    }

    @ApiOperation("导出清欠数据列表")
    @GetMapping("/list/export")
    public void exportDebtsList(HttpServletResponse response, DebtsSectionDto dto) throws IOException {
        List<DebtsSectionVo> list = debtsSectionService.getList(dto);
        List<DebtsSectionExport> debtsSectionExportList = list.stream().map(i -> {
            DebtsSectionExport debtsSectionExport = new DebtsSectionExport();
            BeanUtils.copyProperties(i, debtsSectionExport);
            debtsSectionExport.setCreateTime(i.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
            return debtsSectionExport;
        }).collect(Collectors.toList());

        // 设置响应头，确保浏览器以下载方式处理文件
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置文件名，注意需要对中文进行 URL 编码
        String fileName = URLEncoder.encode("清欠数据列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + fileName + ".xlsx\";" +
                        " filename*=UTF-8''" + fileName + ".xlsx");

        // 使用 EasyExcel 写入数据到输出流
        OutputStream outputStream =  response.getOutputStream();
        EasyExcel.write(outputStream, DebtsSectionExport.class)
                .sheet("清欠数据列表")
                .registerWriteHandler(new HeaderStyleHandler())
                .doWrite(debtsSectionExportList);

        // 关闭流资源
        if (outputStream != null) {
            outputStream.close();
        }
    }
}
